package com.wjw.leetcode;

import com.wjw.common.ListNode;

import java.util.HashSet;
import java.util.Set;

/**
 * linked-list-cycle-ii
 * 环形链表 II
 */
public class leetcode142 {

    // 哈希表
    public ListNode detectCycle1(ListNode head) {
        Set<ListNode> set = new HashSet<ListNode>();
        while (head != null) {
            if (set.contains(head)) {
                return head;
            }
            set.add(head);
            head = head.next;
        }
        return null;
    }

    // 快慢指针
    public ListNode detectCycle(ListNode head) {
        ListNode slow = head, fast = head;
        while (true) {
            if (fast == null || fast.next == null) return null;
            fast = fast.next.next;
            slow = slow.next;
            if (fast == slow) break;
        }

        fast = head;
        while (slow != fast) {
            slow = slow.next;
            fast = fast.next;
        }
        return fast;
    }
}
